package com.enbatis.mybatisplugs.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.enbatis.mybatisplugs.base.BaseServiceImpl;

//import com.enbatis.mybatisplugs.component.LocationSender;
import com.enbatis.mybatisplugs.entity.LocationUser;
import com.enbatis.mybatisplugs.entity.dto.LocationUserDTO;
import com.enbatis.mybatisplugs.entity.vo.SendVO;
import com.enbatis.mybatisplugs.mapper.LocationUserMapper;
import com.enbatis.mybatisplugs.service.LocationUserService;
import com.enbatis.mybatisplugs.toolkit.HttpRequestUtils;
import com.enbatis.mybatisplugs.toolkit.LngLonUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
* 描述：
* @author wangweidong
* @date 2020-01-06 16:13:41
*/

@Service
public class LocationUserServiceImpl extends BaseServiceImpl<LocationUserMapper,LocationUser > implements LocationUserService {


//    @Autowired
//    private LocationSender locationSender;


    @Override
    public boolean locationReceive(String json) {
        if (StringUtils.isBlank(json)){
            return false;
        }

        JSONObject jsonObject = JSONObject.parseObject(json);
        SendVO vo=   jsonObject.toJavaObject(SendVO.class);
        if (null==vo){
            return false;
        }

        LocationUser user = new LocationUser();
        if ("0".equals(vo.getCode())){
            user.setCode(0);
            user.setCompanyId(Long.parseLong(vo.getCompanyId()));
            user.setUsername(vo.getUsername());


            //?ak=t6v7gPZ8DT2KzqwtceFZaGYLoCYle52p&output=json&coordtype=wgs84ll&location=36.314463,120.430593
            if (StringUtils.isNotBlank(vo.getLatitude())&&StringUtils.isNotBlank(vo.getLongitude())){

                double [] lngs = LngLonUtil.gps84_To_bd09(Double.parseDouble(vo.getLatitude()),Double.parseDouble(vo.getLongitude()));
                if (ArrayUtils.isNotEmpty(lngs)&&lngs.length==2){
                    vo.setLatitude(lngs[0]+"");
                    vo.setLongitude(lngs[1]+"");
                }
                user.setLatitude(vo.getLatitude());
                user.setLongitude(vo.getLongitude());

                Map<String,String> map =new HashMap<>();
                map.put("ak","t6v7gPZ8DT2KzqwtceFZaGYLoCYle52p");
                map.put("output","json");
                map.put("location",vo.getLatitude()+","+vo.getLongitude());
                JSONObject object=   HttpRequestUtils.httpGet("http://api.map.baidu.com/reverse_geocoding/v3/",map);
                String address= getAddress(object);
                if (StringUtils.isNotBlank(address)){
                    user.setPlace(address);
                }
            }

            if (StringUtils.isNotBlank(vo.getSendDate())){
                user.setSendDate(dateStringtoDate(vo.getSendDate()));
            }

        }else{
            user.setCode(-1);
            user.setCompanyId(Long.parseLong(vo.getCompanyId()));
            user.setUsername(vo.getUsername());
            user.setError(vo.getError());
            if (StringUtils.isNotBlank(vo.getSendDate())){
                user.setSendDate(dateStringtoDate(vo.getSendDate()));
            }
        }
        return null!=insert(user);
    }

    @Override
    public boolean pushLocationData(String json) {
//        locationSender.sendLocation(json);
        return false;
    }

    @Override
    public List<LocationUserDTO> listLocation(LocationUserDTO locationUser) {
        if (null == locationUser.getSendDateBegin()){
            SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
            String day=  sd.format(new Date());
            String bg= day+" 00:00:00";
            String end= day+" 23:59:59";
            SimpleDateFormat sds=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                locationUser.setSendDateBegin(sds.parse(bg));
                locationUser.setSendDateEnd(sds.parse(end));
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd");
            String date=  sd.format(locationUser.getSendDateBegin());
            String bg= date+" 00:00:00";
            String end= date+" 23:59:59";
            SimpleDateFormat sds=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                locationUser.setSendDateBegin(sds.parse(bg));
                locationUser.setSendDateEnd(sds.parse(end));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        List<LocationUser> list = baseMapper.selectListMapper(locationUser);
        if (CollectionUtils.isEmpty(list)){
            return Lists.newArrayList();
        }
        Map<String,List<LocationUser>> listMap = new HashMap<>();


        for (LocationUser user:list) {
            if (listMap.get(user.getUsername())==null){
                List<LocationUser> mapList = new ArrayList<>();
                mapList.add(user);
                listMap.put(user.getUsername(),mapList);
            }else{
                List<LocationUser> mapList = listMap.get(user.getUsername());
                mapList.add(user);
                listMap.put(user.getUsername(),mapList);
            }
        }
        List<LocationUserDTO> dtos = new ArrayList<>();

        for (Map.Entry<String,List<LocationUser>> s: listMap.entrySet()) {
            LocationUserDTO dto = new LocationUserDTO();
            dto.setUsername(s.getKey());
            dto.setUsersList(s.getValue());
            dtos.add(dto);
        }

        return  dtos;
    }


    public String getAddress(JSONObject object){
        if (null!=object){
            JSONObject result= object.getJSONObject("result");
            if (null!=result){
                JSONObject  addressComponent=  result.getJSONObject("addressComponent");
                if (null!=addressComponent){
                    StringBuffer sb = new StringBuffer();
                    String country=   addressComponent.getString("country");
                    String province=   addressComponent.getString("province");
                    String city=   addressComponent.getString("city");
                    String district=   addressComponent.getString("district");
                    String town=   addressComponent.getString("town");
                    String street=   addressComponent.getString("street");
                    String direction=   addressComponent.getString("direction");
                    String distance=   addressComponent.getString("distance");
                    if (StringUtils.isNotBlank(country)){
                        sb.append(country);
                    }

                    if (StringUtils.isNotBlank(province)){
                        sb.append(province);
                    }


                    if (StringUtils.isNotBlank(city)){
                        sb.append(city);
                    }

                    if (StringUtils.isNotBlank(district)){
                        sb.append(district);
                    }

                    if (StringUtils.isNotBlank(town)){
                        sb.append(town);
                    }

                    if (StringUtils.isNotBlank(street)){
                        sb.append(street);
                    }

                    if (StringUtils.isNotBlank(direction)){
                        sb.append(direction);
                    }

                    if (StringUtils.isNotBlank(distance)){
                        sb.append(distance);
                    }

                    return sb.toString();
                }
            }

        }
        return "";
    }


    public static Date dateStringtoDate(String date) {
        if (StringUtils.isBlank(date)) {
            return null;
        } else {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return sdf.parse(date);
            } catch (Exception var4) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    return sdf.parse(date);
                } catch (Exception var3) {
                    var3.printStackTrace();
                    return null;
                }
            }
        }
    }
}
